/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package backend;

import db.DB;
import db.UserDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Vector;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Lord Makuta
 */
public class accountchange extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        try 
        {
            ServletContext sc = this.getServletContext();
            DB data=new DB();
            Connection conn=null;
            Statement stm=null;
            ResultSet res=null;
            UserDAO usr=(UserDAO)sc.getAttribute("usser");
            
            if (usr==null)
            {
                sc.getRequestDispatcher("/account.jsp").forward(request, response);
                return;
            }
            
            Vector diffs=new Vector();
            
            if (request.getParameter("fname")!=null)
            {
                String fn=request.getParameter("fname");
                String ln=request.getParameter("lname");
                String addr=request.getParameter("address");
                String cred=request.getParameter("credit");
                String email=request.getParameter("email");
                String pass=request.getParameter("pass");
                String city=request.getParameter("city");
                String state=request.getParameter("state");
                String zip=request.getParameter("zip");
                String phone=request.getParameter("phone");
                int plan=Integer.parseInt(request.getParameter("plan"));
                
                try
                {
                    if (!fn.equals(usr.getFirstname()))
                    {
                        diffs.add("FirstName='"+fn+"',");
                    }
                    if (!ln.equals(usr.getLastname()))
                    {
                        diffs.add("LastName='"+ln+"',");
                    }
                    if (!addr.equals(usr.getAddress()))
                    {
                        diffs.add("Address='"+addr+"',");
                    }
                    if (cred!="" && !cred.equals(usr.getCreditCardNumber()))
                    {
                        diffs.add("CreditCardNumber='"+cred+"',");
                    }
                    if (email!="" && !email.equals(usr.getEmail()))
                    {
                        diffs.add("Email='"+email+"',");
                    }
                    if (pass!="" && !pass.equals(usr.getPassword()))
                    {
                        diffs.add("Password='"+pass+"',");
                    }
                    if (!city.equals(usr.getCity()))
                    {
                        diffs.add("City='"+city+"',");
                    }
                    if (!state.equals(usr.getState()))
                    {
                        diffs.add("State='"+state+"',");
                    }
                    if (!zip.equals(usr.getZip()))
                    {
                        diffs.add("ZipCode='"+zip+"',");
                    }
                    if (!phone.equals(usr.getPhone()))
                    {
                        diffs.add("Telephone='"+phone+"',");
                    }
                    if (plan!=usr.getLevel())
                    {
                        diffs.add("Level="+plan+",");
                    }
                    
                    String update="";
                    
                    for (int i=0; i<diffs.size(); i++)
                    {
                        update+=diffs.get(i);
                    }
                    update=update.substring(0, update.length()-1);  //chop off last comma
                    
                    conn=data.getConnection();
                    stm=conn.createStatement();
                    update="UPDATE Users SET "+update+" WHERE Id="+usr.getId();
                    stm.executeUpdate(update);
                    conn.close();
                }
                catch (Exception e)
                {
                    
                }
                
            }
            else if (request.getParameterValues("retMovie")!=null)
            {
                String[] returns=request.getParameterValues("retMovie");
                try
                {
                    conn=data.getConnection();
                    stm=conn.createStatement();
                    
                    String remove="UPDATE Rental SET ReturnDate=NOW() WHERE CustomerId="+usr.getId()+" AND MovieId=";
                    for (int i=0; i< returns.length; i++)
                    {
                        stm.executeUpdate(remove+returns[i]);
                    } 
                    res=stm.executeQuery("SELECT Rating FROM Users WHERE Id="+usr.getId());
                    res.next();
                    if (res.getInt(1)<5)
                    {
                        stm.executeUpdate("UDPATE Users SET Rating="+(res.getInt(1)+1)+" WHERE Id="+usr.getId());
                    }
                }
                catch (Exception e)
                {
                    
                }
            }
            else if (request.getParameterValues("qMovie")!=null)
            {
                String[] returns=request.getParameterValues("qMovie");
                try
                {
                    conn=data.getConnection();
                    stm=conn.createStatement();
                    
                    
                    String ret="DELETE FROM MovieQ WHERE AccountId="+usr.getId()+" AND MovieId=";
                    
                    for (int i=0; i< returns.length; i++)
                    {
                        stm.executeUpdate(ret+returns[i]);
                        res=stm.executeQuery("SELECT NumCopies FROM Movie WHERE Id="+returns[i]);
                        res.next();
                        int nums=res.getInt(1)+1;
                        stm.execute("UPDATE Movie SET NumCopies="+nums+" WHERE Id="+returns[i]);
                    }
                }
                catch (Exception e)
                {
                    
                }
                
            }
            else if (request.getParameterValues("renMovie")!=null)
            {
                String[] take=request.getParameterValues("renMovie");
                int plan=usr.getLevel();
                int numMv=0;
                try
                {
                    
                    conn=data.getConnection();
                    stm=conn.createStatement();
                    
                    for (int i=0; i< take.length; i++)
                    {
                        res=stm.executeQuery("SELECT COUNT(*) FROM Rental R WHERE ReturnDate IS NOT NULL AND date_format(R.Date, '%m')=date_format(NOW(), '%m') AND date_format(R.Date, '%Y')=date_format(NOW(), '%Y') AND CustomerId="+usr.getId());
                        res.next();
                        numMv=res.getInt(1);
                        boolean renTest1=this.canRentMon(usr.getLevel(), numMv);
                    
                        if (renTest1)
                        {
                            String clear="DELETE FROM MovieQ WHERE AccountId="+usr.getId()+" AND MovieId=";
                            String rent="INSERT INTO Rental (CustomerId, Date, EmployeeId, MovieId) VALUES ("+usr.getId()+", NOW(), -1,";
                        
                            res=stm.executeQuery("SELECT COUNT(*) FROM Rental R WHERE ReturnDate IS NULL AND date_format(R.Date, '%m')=date_format(NOW(), '%m') AND date_format(R.Date, '%Y')=date_format(NOW(), '%Y') AND CustomerId="+usr.getId());
                            res.next();
                            numMv=res.getInt(1);
                            boolean renTest2=this.canRentCount(usr.getLevel(), numMv);
                            
                            if (renTest2)
                            {
                                stm.executeUpdate(clear+take[i]);
                                stm.executeUpdate(rent+take[i]+")");
                            }
                            else
                                renTest1=false;
                        }
                        else
                            i=take.length;
                    }
                }
                catch (Exception e)
                {
                    
                }
                
            }
            /*else if (request.getParameterValues("score")!=null)
            {
                String[] scores=request.getParameterValues("score");
                
                try
                {
                    conn=data.getConnection();
                    stm=conn.createStatement();
                    
                    //String prevCheck="DELETE FROM MovieQ WHERE AccountId="+usr.getId()+" AND MovieId=";
                    String rate="INSERT INTO MovieRatings (CustomerId, MovieId) VALUES ("+usr.getId()+", NOW(), -1,";
                    
                    for (int i=0; i< scores.length; i++)
                    {
                        
                    }
                }
                catch (Exception e)
                {
                    
                }
                
            }*/
            
            sc.getRequestDispatcher("/account.jsp").forward(request, response);
        } 
        finally 
        {            
        }
    }
    
    /**
     * determines whether a user can take another movie out based on the number of movies they are currently renting
     * 
     * @param lv
     * user's rental plan
     * @param curNum
     * number of movies currently withdrawn this month
     * @return 
     */
    public boolean canRentCount(int lv, int curNum)
    {
        if ((lv==0  || lv==1) && curNum==1)
        {
            return false;
        }
        else if (lv==2 && curNum==2)
        {
            return false;
        }
        else if (lv==3 && curNum==3)
        {
            return false;
        }
        else
            return true;
    }
    
    /**
     * determines whether a user can rent anymore movies for this month
     * @param lv
     * @param monNum
     * @return 
     */
    public boolean canRentMon(int lv, int monNum)
    {
        if (lv==0 && monNum==2)
        {
            return false;
        }
        else
            return true;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
